import { Injectable, UseFilters } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { equals } from 'ramda';
import { IdDto } from 'src/common/dto/dto';
import { HttpExceptionFilter } from 'src/common/http-exception.filter';
import { JumpType } from 'src/dictionaries/index.enum';
import { getPagination, throwHttp } from 'src/utlis';
import { isTrue } from 'src/utlis/tools';
import { Repository } from 'typeorm';
import { GetBannerDto, CreateBannerDto, UpdateBannerDto } from './dto/banner.dto';
import { BannerEntity } from './entities/banner.entity';

@Injectable()
export class BannerService {
  constructor(
    @InjectRepository(BannerEntity)
    private bannerEntityRepository: Repository<BannerEntity>,
  ) { }
  async getBannerPage(params: GetBannerDto) {
    try {
      const {
        status,
        jumpType,
      } = params;
      const where: GetBannerDto = {
        status,
        jumpType,
      };
      const { pageSize, pageNum } = getPagination({
        pageSize: params.pageSize,
        pageNum: params.pageNum,
      });
      const [data, total] = await this.bannerEntityRepository.findAndCount({
        where,
        cache: true,
        skip: pageNum * pageSize,
        take: pageSize,
        order: { createDate: 'DESC' },
        relations: ['movies'],
      });
      return {
        data,
        total,
        pageSize,
        pageNum: pageNum + 1,
      };;
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 创建轮播数据 */
  @UseFilters(new HttpExceptionFilter())
  async createBanner(body: CreateBannerDto) {
    try {
      const { img, status, remarks, jumpType, url, sort, moviesId, lang } = body;
      if (equals(jumpType, JumpType.ExternalLinks) && !isTrue(url)) {
        throwHttp('跳转链接不能为空');
        return
      }
      if (equals(jumpType, JumpType.movies)) {
        const data = await this.bannerEntityRepository.findOne({
          where: { moviesId, lang },
          cache: true,
        });
        if (data) {
          return throwHttp('该电影已存在轮播图');;
        }
      }
      const banner = new BannerEntity();
      banner.img = img;
      banner.status = status;
      banner.remarks = remarks;
      banner.jumpType = jumpType;
      banner.moviesId = moviesId;
      banner.sort = sort;
      banner.lang = lang;
      if (equals(jumpType, JumpType.ExternalLinks)) {
        banner.url = url;
      }
      const result = await this.bannerEntityRepository.manager.save(banner);
      if (isTrue(result)) {
        return '创建成功';
      }
      return '创建失败';
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 更新轮播数据 */
  @UseFilters(new HttpExceptionFilter())
  async updateBanner(body: UpdateBannerDto) {
    try {
      const { id, img, status, remarks, jumpType, url, sort, moviesId, lang } = body;
      if (equals(jumpType, JumpType.ExternalLinks) && !isTrue(url)) {
        throwHttp('跳转链接不能为空');
        return
      }
      const BannerInfo = await this.getBannerInfo({
        id,
      });
      if (!isTrue(BannerInfo)) {
        throwHttp('轮播数据不存在');
        return;
      }
      const parmas: any = {
        img, status, remarks, sort, jumpType, lang
      }
      if (equals(jumpType, JumpType.ExternalLinks)) {
        parmas.url = url;
      }
      if (equals(jumpType, JumpType.movies)) {
        parmas.moviesId = moviesId;
      }
      const { affected } = await this.bannerEntityRepository
        .createQueryBuilder()
        .update(BannerEntity)
        .set(parmas)
        .where('id = :id', { id })
        .execute();
      if (affected) {
        return '更新成功';
      }
      throwHttp('更新失败');
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 获取轮播数据详情 */
  @UseFilters(new HttpExceptionFilter())
  async getBannerInfo({ id }) {
    try {
      return await this.bannerEntityRepository.findOne({
        where: { id },
        cache: true,
      });
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 删除轮播数据 */
  @UseFilters(new HttpExceptionFilter())
  async deleteBanner({ id }: IdDto) {
    try {
      const data = await this.getBannerInfo({ id });
      if (!isTrue(data)) {
        throwHttp('轮播数据不存在');
        return;
      }
      await this.bannerEntityRepository.softDelete(id);
      return '删除成功';
    } catch (error) {
      throwHttp(error.message);
    }
  }
}
